package wyp.library.ui.vc;

import java.util.ArrayList;

import wyp.library.R;
import wyp.library.ui.fragment.WypFragment;
import wyp.library.ui.view.WypGroupView;
import wyp.library.ui.view.WypBarItem;
import wyp.library.ui.view.WypGroupView.WypGroupViewDelegate;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.LinearLayout;

public class WypTabBarViewController implements WypGroupViewDelegate {

	private LinearLayout mMainLayout;
	private FragmentManager mFragmentManager;
	private ArrayList<WypBarItem> mItemList;
	private int mFragmentLayoutId;
	private int mTabStatus = -1;
	private int mCurrentIndex = 0;

	public WypTabBarViewController(LinearLayout _linearLayout, FragmentManager _fragmentManager) {
		super();
		this.mMainLayout = _linearLayout;
		this.mFragmentManager = _fragmentManager;
		this.mMainLayout.setBaselineAligned(false);
		this.mMainLayout.setOrientation(LinearLayout.HORIZONTAL);
	}

	public void initData(int _fragmentLayoutId, ArrayList<WypBarItem> _itemList) {
		this.mFragmentLayoutId = _fragmentLayoutId;
		mItemList = _itemList;
		for (WypBarItem _item : mItemList) {
			_item.setDelegate(this);
			this.mMainLayout.addView(_item);
		}
	}

	public void setTabSelection(int _index) {

		try {
			FragmentTransaction _transaction = mFragmentManager.beginTransaction();
			setAnimations(_transaction, _index);
			for (WypBarItem _item : mItemList) {
				if (_item.getFragment() != null) {
					_transaction.hide(_item.getFragment());
					_item.getFragment().onResume();
				}
				_item.setNormal(_transaction);
			}

			WypBarItem _selectItem = mItemList.get(_index);
			if (_selectItem.getFragment() == null) {
				_selectItem.setFragment((WypFragment) _selectItem.getFragmentClass().newInstance());
				_transaction.add(mFragmentLayoutId, _selectItem.getFragment());
			} else {
				_transaction.show(_selectItem.getFragment());
				_selectItem.getFragment().onResume();
			}
			changeHighlight(_selectItem);
			_transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.mCurrentIndex = _index;
	}
	
	public int currentIndex(){
		return this.mCurrentIndex;
	}
	
	protected void changeHighlight(WypBarItem _selectItem){
		_selectItem.setHighlight();
	}

	protected void setAnimations(FragmentTransaction _transaction, int _index) {
		if (mTabStatus < _index || mTabStatus == -1) {
			_transaction.setCustomAnimations(R.anim.wyp_push_left_in, R.anim.wyp_push_left_out);
		} else if (mTabStatus > _index) {
			_transaction.setCustomAnimations(R.anim.wyp_back_left_in, R.anim.wyp_back_right_out);
		}
		mTabStatus = _index;
	}

	@Override
	public void onClick_WypGroupView(WypGroupView _view) {
		int _index = this.mItemList.indexOf(_view);
		if (_index >= 0) {
			setTabSelection(_index);
		}
	}

}
